<template>
  <Page class="bg-[#f5f7fa] min-h-screen">
    <!-- 顶部蓝色渐变背景 -->
    <PageHeader title="申请用户" :showBack="true" :onlyBack="true" />
    <view
      class="fixed top-0 left-0 w-full z-[3] h-[250rpx] bg-gradient-to-b from-[#2196F3] to-[#6ec6ff] rounded-b-[40rpx]">
    </view>

    <!-- 吸顶标题栏 -->
    <view class="fixed left-0 right-0 w-[680rpx] m-auto top-0 z-4 px-[32rpx] pt-[32rpx] pb-[24rpx] bg-transparent">
      <view class="flex items-center justify-end mb-[24rpx]">

        <view class="flex items-center gap-x-[12rpx]">
          <text class="text-[24rpx] text-white/80">共{{ registrationList?.length || 0 }}人</text>
        </view>
      </view>

      <!-- 任务信息卡片 -->
      <view class="bg-white/90 backdrop-blur-sm rounded-[24rpx] p-[24rpx] shadow-lg">
        <view class="flex items-start justify-between mb-[16rpx]">
          <text class="text-[28rpx] font-bold text-[#333] flex-1 mr-[16rpx]">
            {{ receiveData?.position_name || receiveData?.title }}
          </text>
          <view class="px-[12rpx] py-[4rpx] rounded-[12rpx] text-[20rpx] font-medium" :class="taskInfo.statusClass">
            {{ change(receiveData?.status) }}
          </view>
        </view>
        <view class="flex items-center justify-between">
          <text class="text-[24rpx] text-[#666]">{{ receiveData?.salary }}</text>
          <text class="text-[22rpx] text-[#999]">申请截止：{{ receiveData?.deadline }}</text>
        </view>
      </view>
    </view>

    <!-- 申请用户列表 -->
    <view class="pt-[20rpx] pb-[32rpx] px-[32rpx] mt-240px">

      <view v-if="!registrationList.length" class="flex flex-col items-center justify-center py-[100rpx] bg-white rounded-[28rpx]">
        <view class="w-[160rpx] h-[160rpx] bg-gradient-to-br from-[#e3f2fd] to-[#bbdefb] rounded-full flex items-center justify-center mb-[30rpx]">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="dingdan" size="80" color="#2196F3" />
        </view>
        <view class="text-[30rpx] font-medium text-[#666]">暂无申请者</view>
      </view>
      
      <view class="flex flex-col gap-y-[20rpx]">
        <!-- 申请用户卡片 -->
        <view v-for="(applicant, index) in registrationList" :key="applicant.id"
          class="bg-white rounded-[24rpx] p-[24rpx] shadow-md relative" @click="goToUserDetail(applicant)">
          
          <!-- 状态标签 - 右上角 -->
          <view v-if="applicant.status == 10" 
            class="absolute top-[16rpx] right-[16rpx] px-[16rpx] py-[8rpx] rounded-[12rpx] text-[20rpx] font-medium bg-[#ffebee] text-[#f44336] border border-[#ffcdd2]">
            ❌ 已拒绝
          </view>
          <view v-else-if="applicant.status == 11" 
            class="absolute top-[16rpx] right-[16rpx] px-[16rpx] py-[8rpx] rounded-[12rpx] text-[20rpx] font-medium bg-[#e8f5e9] text-[#4caf50] border border-[#c8e6c9]">
            ✅ 已通过
          </view>
          <view v-else 
            class="absolute top-[16rpx] right-[16rpx] px-[16rpx] py-[8rpx] rounded-[12rpx] text-[20rpx] font-medium bg-[#fff3e0] text-[#ff9800] border border-[#ffe0b2]">
            ⏳ 待审核
          </view>
          <!-- 用户基本信息 -->
          <view class="flex items-start justify-between mb-[20rpx]">
            <view class="flex items-center flex-1">

              <view class="flex-1">
                <view class="flex items-center mb-[8rpx]">
                  <text class="text-[28rpx] font-bold text-[#333] mr-[12rpx]">
                    {{ applicant.name }}
                  </text>
                </view>

                <!-- 用户标签 -->
                <view class="flex items-center gap-x-[8rpx] mb-[8rpx]">
                  <view v-for="tag in applicant.tags" :key="tag"
                    class="px-[8rpx] py-[2rpx] bg-[#f5f5f5] text-[#666] text-[20rpx] rounded-[6rpx]">
                    {{ tag }}
                  </view>
                </view>

                <!-- 申请时间 -->
                <text class="text-[22rpx] text-[#999]">
                  申请时间：{{ applicant.create_time }}
                </text>
              </view>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="flex items-center gap-x-[12rpx]">
            <nut-button size="small" type="default" class="flex-1" @click="handleContact(applicant)">
              立即联系
            </nut-button>
            <nut-button v-if="!applicant.status" size="small" type="default" class="flex-1" @click="checkContact(applicant)">
              审核
            </nut-button>
            <nut-button v-else disabled size="small" type="default" class="flex-1">
              已审核
            </nut-button>
          </view>

          <!-- 评价按钮 - 仅对已完成的用户显示 -->
          <view v-if="applicant.status === 'accepted'" class="mt-[12rpx]">
            <nut-button size="small" type="default"
              class="w-full border-yellow-500 text-yellow-500 bg-transparent rounded-[20rpx] py-[12rpx] text-[24rpx] font-medium hover:bg-yellow-50 transition-all duration-200"
              @click="handleEvaluate(applicant)">
              评价用户
            </nut-button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="applicants.length === 0" class="flex flex-col items-center justify-center py-[120rpx]">
        <text class="text-[28rpx] text-[#999] mb-[16rpx]">暂无申请用户</text>
        <text class="text-[24rpx] text-[#ccc]">等待用户申请中...</text>
      </view>
    </view>

    <!-- 评价弹窗 -->
    <EvaluateModal :visible="evaluateModalVisible" :userInfo="currentEvaluateUser" @confirm="handleEvaluateConfirm"
      @cancel="handleEvaluateCancel" />

    <!-- 审核弹窗 -->
    <nut-overlay v-model:visible="auditModalVisible" z-index="3000">
      <view class="audit-modal flex items-center justify-center h-full">
        <view class="audit-content bg-white rounded-[24rpx] w-[600rpx] mx-[32rpx] p-[40rpx]">
          <!-- 弹窗头部 -->
          <view class="audit-header text-center mb-[32rpx]">
            <text class="text-[36rpx] font-bold text-[#333]">申请审核</text>
          </view>

          <!-- 用户信息 -->
          <view class="user-info flex items-center mb-[32rpx] p-[24rpx] bg-[#f8f9fa] rounded-[16rpx]">
            <!-- <image :src="currentAuditUser.avatar || 'http://www.dzgktf.com/templets/default/images/wtyt.jpg'"
              class="w-[80rpx] h-[80rpx] rounded-full mr-[16rpx]" mode="aspectFill" /> -->
            <view class="user-details flex-1">
              <text class="block text-[28rpx] font-medium text-[#333] mb-[8rpx]">申请人：{{ currentAuditUser.name }}</text>
              <text class="text-[24rpx] text-[#666]">申请时间：{{ currentAuditUser.create_time }}</text>
            </view>
          </view>

          <!-- 申请理由 -->
          <!-- <view v-if="currentAuditUser.reason" class="apply-reason mb-[32rpx]">
            <text class="block text-[26rpx] font-medium text-[#333] mb-[12rpx]">📝 申请理由：</text>
            <text class="text-[24rpx] text-[#666] leading-[1.6] block p-[16rpx] bg-[#f8f9fa] rounded-[12rpx]">{{
              currentAuditUser.reason }}</text>
          </view> -->

          <!-- 操作按钮 -->
          <view class="audit-actions flex gap-[16rpx]">
            <nut-button size="large" type="default" class="flex-1" @click="handleAuditCancel">
              取消
            </nut-button>
            
            <nut-button size="large" type="success" class="flex-1" :loading="auditLoading" @click="handleAuditApprove(1)">
              确认
            </nut-button>
          </view>
        </view>
      </view>
    </nut-overlay>
  </Page>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
// import { Overlay as nutOverlay } from "@nutui/nutui-taro";
import { post } from "@/utils/request";
import EmptyState from "./components/EmptyState.vue";
import EvaluateModal from "@/components/EvaluateModal.vue";
import { getCurrentInstance } from "@tarojs/runtime";

/**
 * 申请用户管理列表页面
 * 显示申请用户信息，提供联系和接受申请功能
 */
const type = Taro.getCurrentInstance().router.params.type;
console.log("type 哈哈", type)
const statusMap = {
  1: "发布中",
  2: "进行中",
  3: "待确认完成",
  4: "确认没完成",
  5: "确认已完成",
  6: "已评价",
};

const buttonMap = {
  1: [],
  2: ["聊天", "接受", "拒绝"],
  3: ["聊天", "验证完成", "有纠纷"],
  4: [],
  5: ["去评价"],
  6: [],
};

// 任务信息
const taskInfo = ref({
  title: "超市临时导购员（周末2天）",
  status: "执行中",
  statusClass: "bg-[#f6ffed] text-[#52c41a]",
  amount: "￥180/天",
  deadline: "本周日 22:00",
});

// 申请用户列表
const applicants = ref([
]);

const handleContact = (item) => {
  // 跳转到聊天页面
  console.log('===>',item)
  Taro.navigateTo({
    url:`/pages/message/chat?userId=${item.member_id}&userName=${item.name}`
  })
};  

/**
 * 返回上一页
 */
const handleBack = () => {
  Taro.navigateBack();
};

/**
 * 审核申请用户
 * @param {Object} applicant - 申请用户信息
 */
const checkContact = (applicant) => {
  currentAuditUser.value = applicant;
  console.log("审核用户：", applicant);
  auditModalVisible.value = true;
};

// 评价弹窗相关
const evaluateModalVisible = ref(false);
const currentEvaluateUser = ref({});

// 审核弹窗相关
const auditModalVisible = ref(false);
const currentAuditUser = ref({});
const auditLoading = ref(false);


//获取数据
const receiveData = ref()
const registrationList = ref([])

/**
 * 审核
 */
const handleAuditApprove = async (n) => {
  if (auditLoading.value) return;

  auditLoading.value = true;
  // const type = Taro.getCurrentInstance().router.params.type;
  const urlMaps = {
    0: "/recruitmentDaily/updateSignUp",
    1: "/task/updateSignUp",
    2: "/pages/post/my-publish",
  };

  try {
    let res = await post(urlMaps[type], {
      id: currentAuditUser.value.id,
      status: 1
    })
    if (res.code === 0) {
      // 关闭弹窗并刷新列表
      auditModalVisible.value = false;

      // 刷新申请列表
      const courseId = getCurrentInstance();
      const taskId = courseId.router?.params.taskId || "";
      if (taskId) {
        getSignUpList(taskId);
      }
    } else {
      Taro.showToast({
        title: res.msg || '审核失败',
        icon: 'none',
        duration: 2000
      });
    }
  } catch (error) {
    console.error('审核不通过失败：', error);
    Taro.showToast({
      title: '网络异常，请重试',
      icon: 'none',
      duration: 2000
    });
  } finally {
    auditLoading.value = false;
  }
};

/**
 * 取消审核
 */
const handleAuditCancel = () => {
  auditModalVisible.value = false;
  currentAuditUser.value = {};
};

const handleEvaluate = (applicant) => {
  currentEvaluateUser.value = {
    name: applicant.name,
    avatar: applicant.avatar,
    taskTitle: taskInfo.value.title,
  };
  evaluateModalVisible.value = true;
};

/**
 * 评价确认
 */
const handleEvaluateConfirm = async (evaluateData) => {
  console.log("评价数据：", evaluateData);

  // 显示完整的评价内容
  console.log("评分：", evaluateData.rating);
  console.log("完整评价内容：", evaluateData.comment);
  console.log("选择的标签：", evaluateData.tags);
  console.log("用户信息：", evaluateData.userInfo);

  // 这里可以调用API提交评价
  const res = await post("/task/score", {
    id: evaluateData.userInfo.id,
    score: evaluateData.rating,
    reviewContent: evaluateData.comment,
    tags: evaluateData.tags,
  });

  if (res.code == 0) {
    Taro.showToast({
      title: "评价提交成功",
      icon: "success",
      duration: 2000,
    });
  }
  evaluateModalVisible.value = false;
};

/**
 * 评价取消
 */
const handleEvaluateCancel = () => {
  evaluateModalVisible.value = false;
};

/**
 * 接受申请
 * @param {Object} applicant - 申请用户信息
 */
const handleAccept = (applicant) => {
  // if (applicant.status === 'accepted' || applicant.status === 'rejected') {
  //   return;
  // }

  Taro.showModal({
    title: "确认接受",
    content: `确定要接受 ${applicant.name} 的申请吗？`,
    success: (res) => {
      if (res.confirm) {
        // 更新申请状态
        // applicant.status = 'accepted';
        acceptApplicant(applicant);

        Taro.showToast({
          title: "已提交",
          icon: "success",
          duration: 2000,
        });

        // 这里可以调用API提交接受申请
        console.log("接受申请：", applicant.id);
      }
    },
  });
};

const acceptApplicant = (applicant) => {
  const type = Taro.getCurrentInstance().router.params.type;
  const urlMaps = {
    0: "/recruitmentDaily/updateSignUp",
    1: "/task/confirmExecution",
    2: "/pages/post/my-publish",
  };

  post(urlMaps[type], {
    "id": applicant.id,
    "status": 1
  }).then((res) => {
    console.log("接受申请：", res);
  });
};

/**
 * 拒绝申请
 * @param {Object} applicant - 申请用户信息
 */
const handleReject = (applicant) => {
  if (applicant.status === "accepted" || applicant.status === "rejected") {
    return;
  }

  Taro.showModal({
    title: "确认拒绝",
    content: `确定要拒绝 ${applicant.name} 的申请吗？`,
    success: (res) => {
      if (res.confirm) {
        // 更新申请状态
        applicant.status = "rejected";

        Taro.showToast({
          title: "已提交",
          icon: "success",
          duration: 2000,
        });

        // 这里可以调用API提交拒绝申请
        console.log("拒绝申请：", applicant.id);
      }
    },
  });
};

/**
 * 跳转到用户详情页
 * @param {Object} applicant - 申请用户信息
 */
function goToUserDetail(applicant) {
  // if (!applicant.id) return;
  // Taro.navigateTo({
  //   url: `/pages/mine/other?id=${applicant.id}`
  // });
}

// 页面加载时获取数据
onMounted(() => {
  //获取路由参数的‘id’
  const courseId = getCurrentInstance()
  const taskId = courseId.router?.params.taskId || ""


  if (taskId) {
    // 根据任务ID加载对应的申请用户数据
    console.log("加载任务ID：", taskId);
    // 这里可以调用API获取申请用户列表
  }

  getTheDailyClosingInformation(taskId)

  getSignUpList(taskId)

});

//const id = Taro.getCurrentInstance().router?.params.id;

//获取该订单信息
const getTheDailyClosingInformation = async (taskId) => {
  const urls = {
    0: "/recruitmentDaily/getById",
    1: "/task/detail",
    2: "/recruitment/getById",
  }
  const res = await post(urls[type], {
    id: taskId
  })
  receiveData.value = res.data.columns
}


//更改状态文本
const change = (status) => {
  switch (status) {
    case 1:
      return "招聘中"
    default:
      return "停止招聘"
  }
}

// 申请用户列表
const getSignUpList = async (id) => {
  const urls = {
    0: "/recruitmentDaily/signUpList",
    1: "/task/signUpList",
    2: "/recruitment/signUpList"
  }
  const res = await post(urls[type], {
    id: id,
  });
  if (res.code == 0) {
    registrationList.value = res.data.map(item => ({
      ...item.columns
    }))
    console.log("申请用户列表==>", res.data);
  }
};
</script>
